
#include "system_q.h"

SystemState gsSystem;

void GPIO_Init(void){		
    P1OUT = 0;							/* Port 1 Output Register */
    P1DIR = BIT1 + BIT0;				/* Port 1 Direction Register */
    P1IES = 0;							/* Port 1 Interrupt Edge Select Register */
    P1IFG = 0;							/* Port 1 Interrupt Flag Register */	

    P2OUT = 0;	/* Port 2 Output Register */
    P2IES = 0;							/* Port 2 Interrupt Edge Select Register */
    P2IFG = 0;							/* Port 2 Interrupt Flag Register */

    P3OUT = 0;							/* Port 3 Output Register */
    
    P4OUT = 0;							/* Port 4 Output Register */	
}
/**
 * Timer interrupt with frequency (in Hz)
 * 
 */
void TIMER_A_Init(void){
	
  /* Initialize TimerA and oscillator. ~250Hz */
  TACCTL0 = CCIE;
  TACCR0 = 4001;
  TACTL = TASSEL_2 + ID_3 + MC_1;
  	
}

void Init_8mhz_clock(void)
{
  BCSCTL1 = CALBC1_8MHZ; 
  DCOCTL = CALDCO_8MHZ;
  BCSCTL3 |= LFXT1S_2;                      // LFXT1 = VLO
}


/**
 * void RF_Setup(void)
 * 
 * Configures the USCI_B0 as SPI for RF module
 */
 
 void RF_Setup(void)
 {
 	
 	RF_SPISetup();
 	RF_PowerupReset();
 	writeRFSettings();
 	RF_BurstWrite(RF_CC2500_PATABLE ,paTable, paTableLen);
 	RF_InterruptEnable();
 	
 }

void System_Init(void){
	int i;
	
	gsSystem.StateReg |= INITIALIZE;;			// Initial values for the system
	gsSystem.InterruptReg = 0;
	gsSystem.SystemTick = 0;
	gsSystem.SystemSeconds = 0;
	gsSystem.SystemMinutes = 0;
	gsSystem.SystemHours = 0;
	gsSystem.RX_Buffer_length = PKTLEN;
	for(i=0;i<=11;i++) 	gsSystem.RX_Buffer[i] = 0;
	
	Init_8mhz_clock();
	
	WDTCTL = WDTPW + WDTHOLD;	/* Disable Watchdog */

	COM_Init();  				/* Initialize serial port */
	
	GPIO_Init();				/* GPIO Initializations */

	TIMER_A_Init();
	
	RF_Setup();
	
	TXString("Initialization Complete!\r\n",26);
	
	__bis_SR_register(GIE);		/* Enable Global Interrupts*/	
}

void Manage_Time(void){
	
	gsSystem.SystemTick++;
	if(gsSystem.SystemTick == 250){
		gsSystem.SystemTick = 0;
		gsSystem.SystemSeconds++;
		TXString("S!\r\n",4);
		if(gsSystem.SystemSeconds>60){
			gsSystem.SystemMinutes++;
			TXString("M!\r\n",4);
			if(gsSystem.SystemMinutes>60){
				gsSystem.SystemHours++;
			}
		}
	}
}


void System_Routine(){
	
	if(gsSystem.InterruptReg&TIMER == TIMER )
	{
		Manage_Time();
		
		gsSystem.InterruptReg &= ~TIMER;
		
		if(gsSystem.InterruptReg&SPI == SPI)
		{
			gsSystem.InterruptReg &= ~SPI;
		}
			
	}
}

